﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GCDF.Common.Report;
using GCDF.PL.Common.Report;
using Workflow.Common.ExcelHelp;
using Workflow.Common.Tools;
using Workflow.Dto;
using Workflow.IService;
using Workflow.Model;
using Workflow.Model.Enum;
using Workflow.Resource;
using Workflow.Web.Common;
using System.Data;

namespace Workflow.Web.Controllers
{
    [Localization]
    [UserAuthorize]
    public class MSDEEMController : Controller
    {
        //
		// GET: /MSDPTP/

		public IWorkStatusService WorkStatusService { get; set; }
		public ICaseEEMService CaseEEMService { get; set; }

		public ActionResult Inquiry()
		{
			return View();
		}

		public ActionResult GetData()
		{
			string s = Request["page"] ?? "1";
			string r = Request["rows"];
			string sortfield = Request["sort"];
			string order = Request["order"];
			if (sortfield == null)
				sortfield = "InvoiceNo";
			if (r == null)
				r = "5";
			long count;
			string orderby = order ;
			string folderLevelA = Request["FolderLevelA"];
			string folderLevelB = Request["FolderLevelB"];
			string workStatus = Request["WorkStatus"];
			string fileName = Request["FileName"];
			string invoiceNo = Request["InvoiceNo"];
			string receiveDateFrom = Request["ReceiveDateFrom"];
			string receiveDateTo = Request["ReceiveDateTo"];
			string checkType = Request["CheckType"];
			string payment = Request["Payment"];
			string reason = Request["Reason"];
			
			
			CaseQueryDto caseQueryDto = new CaseQueryDto();
			int d = (int) EnumFolderClass.EEM;
			caseQueryDto.ProcessType = d.ToString();
			caseQueryDto.FolderLevelA = folderLevelA;
			caseQueryDto.FolderLevelB = folderLevelB;
			caseQueryDto.WorkStatus = workStatus;
			caseQueryDto.FileName = fileName;
			caseQueryDto.InvoiceNo = invoiceNo;
			caseQueryDto.ReceiveDateFrom = receiveDateFrom;
			caseQueryDto.ReceiveDateTo = receiveDateTo;
			caseQueryDto.CheckType = checkType;
			caseQueryDto.Payment = payment;
			caseQueryDto.CommentCode = reason;

			//IList<Case> cases = CaseService.GetAllCaseByPage(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
			IList<CaseEEM> cases = CaseEEMService.GetAllCaseByPage(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
		
			IList<CaseViewDto> caseViewDtos = new List<CaseViewDto>();
			foreach (var c in cases)
			{
				caseViewDtos.Add(new CaseViewDto(c.CaseNo.ToString(),
													c.FileName,
													c.CaseMapPropertyEEM == null ? null : c.CaseMapPropertyEEM.Payment == null ? null : c.CaseMapPropertyEEM.Payment.PaymentName,//c.ProcessType.FolderName,
													
													c.FolderLevelA.FolderName,
													c.FolderLevelB == null ? null : c.FolderLevelB.FolderName,
													c.CheckType == null ? null : c.CheckType.FolderName,
													c.InvoiceNo,
													c.WorkStatus.WorkStatusNameEEM,
													c.Operator == null ? null : c.Operator.UserName,
													c.ReceiveDate == null ? null : ((DateTime)c.ReceiveDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												   c.StatusDate == null ? null : ((DateTime)c.StatusDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												   c.StatusOperator == null ? null : c.StatusOperator.UserName,
												   c.BatchNo.Substring(9, 4),
													 c.CommentCode == null ? null : c.CommentCode.JpReason));
			}
			JsonModel<CaseViewDto> JsonModel = new JsonModel<CaseViewDto>();
			JsonModel.total = count.ToString();
			JsonModel.rows = caseViewDtos;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);
		}

		public ActionResult GetWorkStutes(string level)
		{
			var date = WorkStatusService.GetAllWorkStatus();
			date.Insert(0, new WorkStatus() { WorkStatusCode = "", WorkStatusNamePTP = Global.pleaseSelect, WorkStatusName = Global.pleaseSelect, WorkStatusNameEEM = Global.pleaseSelect });
			if (level == "PL")
			{
				date = (from model in date
						where model.WorkStatusCode == ((int)EnumWorkStatus.Reject).ToString() ||
							  model.WorkStatusCode == ((int)EnumWorkStatus.Closed).ToString()
						select model).ToList();
			}
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
			
		}
		public ActionResult GetFolderLevel()
		{
			string pm = Request["id"];
			var date = CaseEEMService.GetFolderClass(pm);

			date.Insert(0, new FolerClass() { FolderCode = "", FolderName = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}

		public ActionResult StatusBox()
		{

			return View();
		}
		public ActionResult GetRecievBox()
		{

			var workStatus = Request["WorkStatus"];
			var receiveDate = Request["ReceiveDate"];
			var checkType = Request["CheckType"];

			CaseMonitorQueryDto caseMonitorQueryDto = new CaseMonitorQueryDto();
			caseMonitorQueryDto.WorkStatus = workStatus;
			caseMonitorQueryDto.ReceiveDate = receiveDate;
			caseMonitorQueryDto.CheckType = checkType;

			var data = CaseEEMService.GetCaseMonitor(caseMonitorQueryDto);
			var totalf7 = data.Sum(x => x.f7);
			var totalf8 = data.Sum(x => x.f8);
			var totalf9 = data.Sum(x => x.f9);
			var total5 = data.Sum(x => x.total5);
			var totalf10 = data.Sum(x => x.f10);
			var totalf11 = data.Sum(x => x.f11);
			var totalf12 = data.Sum(x => x.f12);
			var totalf13 = data.Sum(x => x.f13);
			var totalf14 = data.Sum(x => x.f14);
			var totalf15 = data.Sum(x => x.f15);
			var totalf16 = data.Sum(x => x.f14);
			var totalf6 = data.Sum(x => x.total6);
			var allTotal = data.Sum(x => x.totlePage);
		    data = data.OrderBy(x => x.batch).ToList();

			//var totalz3 = data.Sum(x => x.z3);
			//var totalAll = data.Sum(x => x.total);
			EEMCaseMonitorDto caseMonitorDto = new EEMCaseMonitorDto();
			caseMonitorDto.id = "1";
			caseMonitorDto.region = string.IsNullOrEmpty(receiveDate) ? ToolsHelper.GetTimeZoneNow().ToString("yyyy/MM/dd") : receiveDate; /////////当前选择时间
			caseMonitorDto.f7 = totalf7;
			caseMonitorDto.f8 = totalf8;
			caseMonitorDto.f9 = totalf9;
			caseMonitorDto.total5 = total5;
			caseMonitorDto.f10 = totalf10;
			caseMonitorDto.f11 = totalf11;
			caseMonitorDto.f12 = totalf12;
			caseMonitorDto.f13 = totalf13;
			caseMonitorDto.f14 = totalf14;
			caseMonitorDto.f15 = totalf15;
			caseMonitorDto.f16 = totalf16;
			caseMonitorDto.total6 = totalf6;
			caseMonitorDto.totlePage = allTotal;
			data.Insert(0, caseMonitorDto);
			JsonModel<EEMCaseMonitorDto> JsonModel = new JsonModel<EEMCaseMonitorDto>();
			JsonModel.total = "4";
			JsonModel.rows = data;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);


		}

		public ActionResult GetClassA()
		{
			string pm = Request["id"];
			var date = CaseEEMService.GetFolderClass(pm);

			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}

		public ActionResult ExportCase()
		{
			try
			{
				string folderLevelA = Request["FolderLevelA"];

				string workStatus = Request["WorkStatus"];
				string fileName = Request["FileName"];
				string invoiceNo = Request["InvoiceNo"];
				string receiveDateFrom = Request["ReceiveDateFrom"];
				string receiveDateTo = Request["ReceiveDateTo"];
				//string operatorId = Request["OperatorID"];
				string folderLevelB = Request["FolderLevelB"];
				string checkType = Request["CheckType"];
				string payment = Request["Payment"];
				string reason = Request["Reason"];

				CaseQueryDto caseQueryDto = new CaseQueryDto();
				int d = (int)EnumFolderClass.EEM;
				caseQueryDto.ProcessType = d.ToString();
				caseQueryDto.FolderLevelA = folderLevelA;
				caseQueryDto.FolderLevelB = folderLevelB;
				caseQueryDto.CheckType = checkType;
				caseQueryDto.WorkStatus = workStatus;
				caseQueryDto.FileName = fileName;
				caseQueryDto.InvoiceNo = invoiceNo;
				caseQueryDto.ReceiveDateFrom = receiveDateFrom;
				caseQueryDto.ReceiveDateTo = receiveDateTo;
				//caseQueryDto.OperatorId = operatorId;
				caseQueryDto.Payment = payment;
				caseQueryDto.CommentCode = reason;

				IList<CaseEEM> cases = CaseEEMService.GetAllCase(caseQueryDto);

				ExportExcel(cases);

				return Json(new { Success = true, Message = "" }, "text/html", JsonRequestBehavior.AllowGet);

			}
			catch (IndexOutOfRangeException indexOutOfRangeException)
			{
				return Json(new { Success = false, Message = indexOutOfRangeException.Message }, "text/html", JsonRequestBehavior.AllowGet);

			}
			catch (Exception ex)
			{
				var debug = ConfigurationManager.AppSettings["DebugFlag"];

				if (debug == "on")
				{
					return Json(new { Success = false, Message = ex.Message }, "text/html", JsonRequestBehavior.AllowGet);

				}
				else
				{
					return Json(new { Success = false, Message = Global.ActiveFalse }, "text/html", JsonRequestBehavior.AllowGet);
				}
			}
		}

		private void ExportExcel(IList<CaseEEM> cases)
		{

			try
			{
				var reportList = cases.Select(x => new
				{
					x.CaseNo,
					x.BatchNo,
					x.InvoiceNo,
					x.FileName,
					FolderLevelA = x.FolderLevelA.FolderName,
					FolderLevelB = x.FolderLevelB.FolderName,
					CheckType = x.CheckType.FolderName,
					ReceiveDate = x.ReceiveDate == null ? null : ((DateTime)x.ReceiveDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
					x.WorkStatus.WorkStatusNameEEM,
					StatusDate = x.StatusDate == null ? null : ((DateTime)x.StatusDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
					StatusOperator = x.StatusOperator == null ? String.Empty : x.StatusOperator.UserName,
					x.StatusComment,
					Operator = x.Operator == null ? String.Empty : x.Operator.UserName,
					PaymentEEM = x.CaseMapPropertyEEM == null ? null : x.CaseMapPropertyEEM.Payment == null ? null : x.CaseMapPropertyEEM.Payment.PaymentName,
					Reason = x.CommentCode == null ? null : x.CommentCode.JpReason
				});

				DataTable dataTable = ToolsHelper.ToDataTable(reportList.ToList());

				string path = Server.MapPath("~/ReportTemplate/DATA_BASE_EEM.xls");
				string pathTemp = Server.MapPath("~/TempFiles/" + ToolsHelper.GetTimeZoneNow().ToString("yyyyMMddhhmmss") + ".xls");
				ReportForm reportForm = new ReportForm();
				reportForm.IReport.OpenOneSheet(path);
				reportForm.IReport.WorkSheetName = "DATA BASE";
				reportForm.IReport.MaxRowCount = 20000 + 4;
				DrawSheet(dataTable, reportForm.IReport);
				reportForm.IReport.ExportToExcel(pathTemp);
				

				var file = new FileInfo(pathTemp);
				Response.Clear();
				Response.Buffer = true;
				Response.Charset = "";
				Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(ToolsHelper.GetTimeZoneNow().ToString("yyyyMMddhhmmss") + ".xls"));
				//Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文

				Response.WriteFile(file.FullName);
				Response.End();
				System.IO.File.Delete(pathTemp);
			}
			catch (Exception ex)
			{

				throw ex;
			}

		}


		private void DrawSheet(System.Data.DataTable dtReport, GCDF.Common.Report.AdapterInterFace.IReport iReport)
		{
			MutiDimensionAndDetailReportDrawer drawer = new MutiDimensionAndDetailReportDrawer(iReport);

			drawer.AddColumn(iReport.GetText(1, 1).ToString(), "CaseNo");
			drawer.AddColumn(iReport.GetText(1, 2).ToString(), "BatchNo");
			drawer.AddColumn(iReport.GetText(1, 3).ToString(), "InvoiceNo");
			drawer.AddColumn(iReport.GetText(1, 4).ToString(), "FileName");
			drawer.AddColumn(iReport.GetText(1, 5).ToString(), "FolderLevelA");
			drawer.AddColumn(iReport.GetText(1, 6).ToString(), "FolderLevelB");
			drawer.AddColumn(iReport.GetText(1, 7).ToString(), "CheckType");
			drawer.AddColumn(iReport.GetText(1, 8).ToString(), "ReceiveDate");
			drawer.AddColumn(iReport.GetText(1, 9).ToString(), "WorkStatusNameEEM");
			drawer.AddColumn(iReport.GetText(1, 10).ToString(), "StatusDate");
			drawer.AddColumn(iReport.GetText(1, 11).ToString(), "StatusOperator");
			drawer.AddColumn(iReport.GetText(1, 12).ToString(), "PaymentEEM");
			drawer.AddColumn(iReport.GetText(1, 13).ToString(), "Reason");
			drawer.AddColumn(iReport.GetText(1, 14).ToString(), "StatusComment");
			drawer.AddColumn(iReport.GetText(1, 15).ToString(), "Operator");

			drawer.FormatDescriptionCollection = FormatDescriptionCollection.CreateDefault();
			drawer.DrawReport(1, 1, dtReport);
			iReport.DrawLine(2, dtReport.Rows.Count, 1, 15);
		}

	}
   
}
